package com.mandroid.forecast.db;

import static com.mandroid.forecast.util.Constants.CREATE_TABLE;
import static com.mandroid.forecast.util.Constants.FORECAST_ROID;
import static com.mandroid.forecast.util.Constants.LOCATION_TABLE_NAME;
import static com.mandroid.forecast.util.Constants.VERSION;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.mandroid.forecast.util.Utils;

public class ForecastDao extends SQLiteOpenHelper{
	
	public static final String[] COLUMNS= new String[]{"code", "name","woeid", "qry"};

	public ForecastDao(Context context) {
		super(context, FORECAST_ROID, null, VERSION);
	}
	
	public void insertLocation(String location, String woeid) {
		if(Utils.isNullOrEmpty(woeid)||Utils.isNullOrEmpty(location)){
			return;
		}
		SQLiteDatabase db = this.getWritableDatabase();
	
		ContentValues values = new ContentValues();
		values.put("code", location.toUpperCase());
		values.put("name", location);
		values.put("woeid", woeid);
		values.put("qry", "");
		db.insert(LOCATION_TABLE_NAME, null, values);
		db.close();
	}
	
	public String queryWoeid(String location){
		if (Utils.isNullOrEmpty(location)) {
			return null;
		}
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.query(LOCATION_TABLE_NAME, new String[]{ }, null, null, null, null, null);

//		Cursor cursor = db.query(LOCATION_TABLE_NAME, new String[]{ }, "code = '"+location.toUpperCase()+"'", null, null, null, null);
		String result = null;
		if(cursor.getCount() > 0) {
			cursor.moveToFirst();
			int index = cursor.getColumnIndex("woeid");
			result = cursor.getString(index);
			cursor.close();
		}
		db.close();
		return result;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String createStatement =getCreateTableStatement(LOCATION_TABLE_NAME, COLUMNS);
		db.execSQL(createStatement);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	public static String getCreateTableStatement(String tableName, String[] columns) {
		
		if (Utils.isNullOrEmpty(tableName) || columns == null) {
			return null;
		}
		StringBuilder createStatement = new StringBuilder(CREATE_TABLE);
		createStatement.append(tableName);
		createStatement.append(" (");
		for (int i = 0; i < columns.length; i++) {
			createStatement.append(columns[i]).append(" TEXT");
			if ( i < columns.length - 1) {
				createStatement.append(", ");
			}
		}
		createStatement.append(")");
		return createStatement.toString();
	}

}
